package com.manli.api.service;

import com.manli.api.base.exception.MyException;
import com.manli.api.dao.UserDao;
import com.manli.api.dao.UserRoleDao;
import com.manli.api.dto.User;
import com.manli.api.dto.UserRole;
import com.manli.api.pojo.QueryParams;
import com.manli.api.pojo.QueryParamsUser;
import com.manli.api.util.*;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.stereotype.Service;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import java.util.List;
import com.manli.api.pojo.Result;
import com.manli.api.pojo.SessionInfo;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import com.manli.api.dao.ViewUserDao;
import com.manli.api.dto.ViewUser;
import com.manli.api.enums.ResultEnums;

import org.springframework.transaction.annotation.Transactional;


@Service("viewUserService")
public class ViewUserService {
    @Autowired
    ViewUserDao viewUserDao;
    @Autowired
    UserDao userDao;
    @Autowired
    UserRoleDao userRoleDao;
    @Autowired
    SessionInfoUtils sessionInfoUtils;
    @Autowired
    SQLManager sqlManager;

    
    public Result queryPage(QueryParamsUser params, HttpServletRequest request) {
    	SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);

    	StringBuffer sql = new StringBuffer("select * from view_user where 1=1 ");
        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getUsername())?"":" and username like '%" + params.getUsername() + "%'");
        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getRoleId())?"":" and role_id = " + params.getRoleId());
        sql.append(QueryParamsMapUtil.paramIsEmpty(params.getStatus())?"":" and status = " + params.getStatus()+" ");
        sql.append(sessionInfo.getBranchId() == 1?"":" and branchId = " + sessionInfo.getBranchId() +" ");
        sql.append(" order by status desc , user_id desc  ");
        SQLReady sqlReady = new SQLReady(sql.toString());

        PageQuery<ViewUser> pageQuery = new PageQuery<ViewUser>(params.getPage(),params.getLimit());
        PageQuery<ViewUser> query =sqlManager.execute(sqlReady,ViewUser.class,pageQuery);
        return ResultUtil.success(query.getList(),query.getTotalRow());
    }

    
    public Result queryAll() {
        List<ViewUser> list = viewUserDao.all();
        return ResultUtil.success(list);
    }

    
    public Result getById(Integer userId) {
        ViewUser viewUser = viewUserDao.single(userId);
        return ResultUtil.success(viewUser);
    }

    @Transactional
    public Result save(ViewUser viewUser,HttpServletRequest request) throws Exception{
    	SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
    	/**
    	 * 校验同一个商户下不能重名
    	 */
    	String sql = "select 1 from user where username = ? ";
    	List<User> checkHasUser = userDao.execute(
                sql,
    			viewUser.getUsername());
    	if(checkHasUser.size()>0) {
    		throw new MyException(-1,"用户名重复");
    	}

        //判断值为空
        ObjectEmptyUtil.userIsEmpty(viewUser);

        User user = new User();
        user.setUsername(viewUser.getUsername());
        user.setPassword(Encrypt.encrypt(viewUser.getPassword()));
        user.setStatus(1);
        user.setBranchId(viewUser.getBranchId());
        user.setPartnerId(viewUser.getPartnerId());
        user.setUserPhone(viewUser.getUserPhone());
        user.setRealName(viewUser.getRealName());
        int id = userDao.insertReturnKey(user).getInt();

        UserRole userRole = new UserRole();
        userRole.setRoleId(viewUser.getRoleId());
        userRole.setUserId(id);
        userRoleDao.insert(userRole);

        return ResultUtil.success();
    }

    @Transactional
    public Result updateById(ViewUser viewUser) throws Exception{
        //判断值为空
        ObjectEmptyUtil.userIsEmpty(viewUser);

        String sql = "select 1 from user where username = ?  and user_id != ?";
        List<User> checkHasUser = userDao.execute(
                sql,
                viewUser.getUsername(),viewUser.getUserId());
        if(checkHasUser.size()>0) {
            throw new MyException(-1,"用户名重复");
        }

        User user = new User();
        user.setUserId(viewUser.getUserId());
        user.setUsername(viewUser.getUsername());
        user.setPassword(viewUser.getPassword() == null?null:Encrypt.encrypt(viewUser.getPassword()));
        user.setStatus(viewUser.getStatus());
        user.setBranchId(viewUser.getBranchId());
        user.setPartnerId(viewUser.getPartnerId());
        user.setUserPhone(viewUser.getUserPhone());
        user.setRealName(viewUser.getRealName());
        userDao.updateTemplateById(user);

        userRoleDao.executeUpdate("update user_role set role_id = ? where user_id = ?",viewUser.getRoleId(),viewUser.getUserId());
        return ResultUtil.success();
    }

    @Transactional
    public Result removeById(Integer userId) {
        viewUserDao.deleteById(userId);
        return ResultUtil.success();
    }

    @Transactional
    public Result removeByIds(List<Integer> ids) {
        for (Integer id:ids) {
            viewUserDao.deleteById(id);
        }
        return ResultUtil.success();
    }



}
